<script setup lang="ts">
import { URL_CONFIGS, ADDRESS } from '@/constants'
import { ElTable } from 'element-plus'
import { ImageService } from '@supermapgis/iclient-mapboxgl'
import initDraw from '@/utils/draw'
import * as turf from '@turf/turf'
import http from '@/utils/http'
import mapboxgl from 'mapbox-gl'

interface ImgData {
  id: string
  fileName: string
  addTime: string
  bbox: number[]
}

const loading = ref(false)
const imageService = new ImageService(URL_CONFIGS.SICHUAN_IMAGESERVICE_URL)
const imgLayerMap: Map<string, string> = new Map()
let draw: MapboxDraw
let regionFeature: any = null
let popup: any = null
const input = ref('')
const restaurants = ref<{ value: string }[]>(ADDRESS)
const multipleTableRef = ref<InstanceType<typeof ElTable>>()
const imgData = ref<ImgData[]>([])

function querySearch(queryString: string, cb: any) {
  const results = queryString ? restaurants.value.filter(createFilter(queryString)) : restaurants.value
  cb(results)
}

function createFilter(queryString: string) {
  return (restaurant: { value: string }) => restaurant.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0
}

onMounted(() => (draw = initDraw()))

async function queryImg() {
  loading.value = true
  if (map.getLayer('sichuan-region')) {
    map.removeLayer('sichuan-region')
    map.removeSource('sichuan-region')
  }
  const postData = {}
  let regionGeojson: GeoJSON.FeatureCollection<GeoJSON.Point> | null = null
  try {
    if (regionFeature) {
      postData['bbox'] = turf.bbox(regionFeature.geometry)
    } else if (input.value) {
      const queryOption = {
        getFeatureMode: 'SQL',
        datasetNames: ['SiChuan:chengdu'],
        queryParameter: { attributeFilter: `区县名称 = '${input.value}'` }
      }
      regionGeojson = await http.post<GeoJSON.FeatureCollection<GeoJSON.Point>>(URL_CONFIGS.SICHUAN_DATA_URL, queryOption)
      postData['bbox'] = turf.bbox(regionGeojson)
    }
    const {
      result: { features }
    } = await imageService.search(postData)
    features.forEach((feature) => {
      const id = `${feature.collection}-${feature.id}`
      const { smfilename: fileName, addtime: addTime } = feature.properties
      imgData.value.push({ id, fileName, addTime, bbox: feature.bbox })
    })
  } catch (error) {
    throw new Error(error instanceof Error ? error.message : '查询影像失败')
  } finally {
    loading.value = false
  }
  if (Object.keys(postData).length !== 0) map.fitBounds(postData['bbox'], { padding: 200 })
  if (regionGeojson) {
    map.addSource('sichuan-region', {
      type: 'geojson',
      data: regionGeojson
    })
    map.addLayer({
      id: 'sichuan-region',
      type: 'fill',
      source: 'sichuan-region',
      paint: {
        'fill-color': 'rgba(255, 0, 0, 0.6)',
        'fill-outline-color': '#2ae815'
      }
    })
    const center = turf.center(regionGeojson)
    popup = new mapboxgl.Popup().setText(regionGeojson.features[0].properties!.区县名称).setLngLat(center.geometry.coordinates).addTo(map)
  }
}

function selectChange(selectedRows: ImgData[], selectedRow: ImgData) {
  if (selectedRows.length > 0 && !imgLayerMap.has(selectedRow.id)) {
    const url = `${URL_CONFIGS.SICHUAN_IMAGESERVICE_URL}/collections/sichuan/tile.png?z={z}&x={x}&y={y}&transparent=true&names=${selectedRow.fileName}`
    map.addLayer(
      {
        id: selectedRow.id,
        type: 'raster',
        source: {
          type: 'raster',
          tiles: [url]
        }
      },
      map.getLayer('sichuan-region') ? 'sichuan-region' : null
    )
    imgLayerMap.set(selectedRow.id, selectedRow.id)
  } else if (selectedRows.length === 0 || imgLayerMap.has(selectedRow.id)) {
    map.removeLayer(selectedRow.id)
    map.removeSource(selectedRow.id)
    imgLayerMap.delete(selectedRow.id)
  }
}

function handleSelectAll(selectedRows: ImgData[]) {
  if (selectedRows.length === 0) {
    imgLayerMap.forEach((imgLayer) => {
      map.removeLayer(imgLayer)
      map.removeSource(imgLayer)
    })
    imgLayerMap.clear()
  } else {
    selectedRows.forEach((selectedRow: ImgData) => {
      if (!imgLayerMap.has(selectedRow.id)) {
        const url = `${URL_CONFIGS.SICHUAN_IMAGESERVICE_URL}/collections/sichuan/tile.png?z={z}&x={x}&y={y}&transparent=true&names=${selectedRow.fileName}`
        map.addLayer(
          {
            id: selectedRow.id,
            type: 'raster',
            source: {
              type: 'raster',
              tiles: [url]
            }
          },
          map.getLayer('sichuan-region') ? 'sichuan-region' : null
        )
        imgLayerMap.set(selectedRow.id, selectedRow.id)
      }
    })
  }
  removeSearchBoxLayer()
}

function rowDoubleClick(selectedRow: ImgData) {
  if (imgLayerMap.has(selectedRow.id)) map.fitBounds(selectedRow.bbox, { padding: 200 })
  addSearchBoxLayer(selectedRow.bbox)
}

function addSearchBoxLayer(bbox: number[]) {
  removeSearchBoxLayer()
  map.addLayer({
    id: 'polygonCoordinates',
    type: 'fill',
    source: {
      type: 'geojson',
      data: {
        type: 'Feature',
        geometry: {
          type: 'Polygon',
          coordinates: [
            [
              [bbox[0], bbox[1]],
              [bbox[2], bbox[1]],
              [bbox[2], bbox[3]],
              [bbox[0], bbox[3]],
              [bbox[0], bbox[1]]
            ]
          ]
        }
      }
    },
    paint: { 'fill-outline-color': '#ff0000', 'fill-color': 'rgba(0,0,0,0.2)' }
  })
}

function removeSearchBoxLayer() {
  if (map.getLayer('polygonCoordinates')) {
    map.removeLayer('polygonCoordinates')
    map.removeSource('polygonCoordinates')
  }
}

function reset() {
  removeSearchBoxLayer()
  input.value = ''
  if (map.getLayer('sichuan-region')) {
    map.removeLayer('sichuan-region')
    map.removeSource('sichuan-region')
  }
  if (popup) popup.remove()
  imgLayerMap.forEach((imgLayer) => {
    map.removeLayer(imgLayer)
    map.removeSource(imgLayer)
  })
  imgLayerMap.clear()
  clearPlotLayer()
  imgData.value = []
}

function drawRegion(type) {
  reset()
  map.on('draw.create', function (e) {
    regionFeature = e.features[0]
  })
  if (type === 'Box') {
    draw.changeMode('draw_rectangle_drag')
  } else {
    const polygonButton = document.querySelector('.mapbox-gl-draw_polygon') as HTMLElement
    if (polygonButton) polygonButton.click()
  }
}

function clearPlotLayer() {
  if (regionFeature) draw.delete(regionFeature.id)
  regionFeature = null
}
</script>

<template>
  <div class="img">
    <div class="title">影像管理</div>
    <div class="img-container">
      <div class="img-query">
        <span>行政区检索:</span>
        <el-autocomplete size="small" v-model="input" :fetch-suggestions="querySearch" :trigger-on-focus="false" clearable style="width: 175px" placeholder="区县名称" />
      </div>
      <div class="buttom-panel">
        <el-button color="#2B333E" size="small" @click="drawRegion('Polygon')">多边形检索</el-button>
        <el-button color="#2B333E" size="small" @click="drawRegion('Box')">矩形检索</el-button>
        <el-button color="#2B333E" size="small" @click="queryImg">查询</el-button>
        <el-button color="#2B333E" size="small" @click="reset">重置</el-button>
      </div>
      <div class="img-table">
        <el-table
          v-loading="loading"
          size="small"
          stripe
          ref="multipleTableRef"
          :data="imgData"
          height="25vh"
          style="width: 100%"
          @select="selectChange"
          @row-dblclick="rowDoubleClick"
          @select-all="handleSelectAll">
          <el-table-column type="selection" width="25" />
          <el-table-column prop="id" label="id" width="80" />
          <el-table-column prop="fileName" label="文件名称" />
          <el-table-column prop="addTime" label="添加时间" />
        </el-table>
      </div>
    </div>
  </div>
</template>

<style lang="scss" scoped>
.img {
  position: absolute;
  top: 54vh;
  // height: 197px;
  width: 327px;
  left: 8px;
  z-index: 9;
  border-radius: 6px;
  background-color: #0a1831a0;
  -webkit-user-select: none;
  -moz-user-select: none;
  -ms-user-select: none;
  user-select: none;

  .title {
    height: 30px;
    margin-bottom: 5px;
    padding: 3px;
    font-size: 18px;
    font-weight: bold;
    color: #fff;
  }

  .img-container {
    display: flex;
    flex-direction: column;
    color: #ccc;

    .buttom-panel {
      margin-top: 10px;
      margin-left: 20px;
    }

    .img-query {
      display: flex;
      align-items: center;
      margin-left: 20px;
    }

    .img-table {
      position: relative;
      width: 100%;
      margin-bottom: 5px;
      padding: 10px;

      :deep(.el-table),
      :deep(.el-table__expanded-cell) {
        background-color: transparent;
        color: #93dcfe;
      }

      :deep(.el-table th) {
        background-color: #031c488f;
        user-select: none;
      }
      :deep(.el-table thead) {
        height: 10px;
      }

      // 表格内背景颜色
      :deep(.el-table tr),
      :deep(.el-table td) {
        background-color: transparent;
        border: 0px;
        color: #ffffffaf;
        height: 5px;
        font-family:
          Source Han Sans CN Normal,
          Source Han Sans CN Normal-Normal;
        font-weight: Normal;
      }

      // 修改高亮当前行颜色
      :deep(.el-table tbody tr:hover) > td {
        background: #0f4d99 !important;
      }

      // 表格斑马自定义颜色
      :deep(.el-table--striped .el-table__body tr.el-table__row--striped td) {
        background: #1f4b5c8e;
      }
    }

    span {
      width: 100px;
      margin-right: 10px;
    }
  }
}
</style>
